import React, { useState } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Card, Alert, Table, Select, Switch, Icon } from 'antd';
import { GRADE, NEWAUTH } from '@/pages/Organization/OrgFlow/constant';
import { replaceTreeNode, removeEmptyChildren, tree2array } from '@/utils/tree';
import { TreeSelectGroup } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import { useRequest } from '@/hooks';
import { fetchManageList, fetchFunctionList } from '@/pages/Setting/Privilege/services';
import FooterButton from './FooterButton';
import styles from '../index.less';

const getLocalRows = () => {
    const temp = localStorage.getItem('authEditId');
    if (temp) {
        return JSON.parse(temp);
    }
    return [];
};

const setDraftData = data =>
    data.map(item => {
        const result = { ...item };
        const { children, draft } = result;
        if (Array.isArray(children) && children.length) {
            result.children = setDraftData(children);
        } else {
            delete result.children;
        }
        if (Object.keys(draft).length > 0) {
            draft.content.map(v => {
                if (result.resourceCode === v.resourceCode) {
                    result.isEnable = v.isEnable !== 0;
                    result.functionGrade = v.functionGrade;
                    result.roleCodes = v.roleCodes;
                }
                return '';
            });
        }
        return result;
    })


const BatchEdit = () => {
    const [rowsId] = React.useState(getLocalRows());
    const [rows, setRows] = React.useState([]);
    const [oldDate, setOldDate] = React.useState([]);
    const [expandAllRows, setExpandAllRows] = useState([]); // 展开项控制

    const saveData = React.useMemo(() => {
        const mapList = tree2array(removeEmptyChildren(rows));
        const resources = mapList.map(item => ({
            resourceCode: item.resourceCode,
            functionGrade: item.functionGrade,
            isEnable: item.isEnable ? 1 : 0,
            roleCodes: item.roleCodes
        }));
        return {
            draftCode: '', // 更新传
            version: '', // 更新传
            resources
        };
    }, [oldDate, rows]);
    const submitData = React.useMemo(() => {
        const mapList = tree2array(removeEmptyChildren(rows));
        const oldList = tree2array(removeEmptyChildren(oldDate));
        return mapList.map((item, index) => ({
            resourceCode: item.resourceCode,
            functionGrade: item.functionGrade,
            isEnable: item.isEnable,
            operationType: '1',
            roleCodes: item.roleCodes,

            oldDate: {
                constData: oldList?.[index],
                resourceCode: oldList?.[index]?.resourceCode,
                functionGrade: oldList?.[index]?.functionGrade,
                isEnable: oldList?.[index]?.isEnable,
                operationType: '1',
                roleCodes: oldList?.[index]?.roleCodes
            }
        }));
    }, [oldDate, rows]);

    // 获取功能权限数据
    const { loading } = useRequest(
        () => {
            const params = {
                resourceCodes: rowsId
            };

            return fetchFunctionList(params);
        },
        {
            refreshDeps: [rowsId],
            onSuccess: v => {
                const { code, data } = v;
                if (code === 10000) {
                    setExpandAllRows(data.map(item => item.resourceCode));
                    setRows(setDraftData(data));
                    setOldDate(data);
                }
            }
        }
    );

    // 获取功能权限数据
    const { run: getFunctionList } = useRequest(
        () => {
            const params = {
                resourceCodes: rowsId
            };

            return fetchFunctionList(params);
        },
        {
            manual: true
        }
    );

    const handleRowDataChange = record => {
        const { resourceCode } = record;
        const result = replaceTreeNode(rows, 'resourceCode', resourceCode, record);
        setRows(result);
    };

    const { data: manageList } = useRequest(fetchManageList);

    const columns = [
        {
            title: '功能',
            dataIndex: 'nameZh',
            key: 'nameZh'
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: value => NEWAUTH[value]
        },
        {
            title: '状态',
            dataIndex: 'isEnable',
            key: 'isEnable',
            render: (value, record) => (
                <div className={styles.functionStatusWrapper}>
                    {typeof value === 'boolean' || typeof value === 'number' ? (
                        <Switch
                            onChange={v => {
                                const result = { ...record, isEnable: v };
                                handleRowDataChange(result);
                            }}
                            checked={value}
                        />
                    ) : (
                        <Icon type="minus" />
                    )}
                </div>
            )
        },
        {
            title: '等级',
            dataIndex: 'functionGrade',
            key: 'functionGrade',
            render: (value, record) => (
                <Select
                    value={value}
                    onChange={rank => {
                        const result = { ...record, functionGrade: rank };
                        handleRowDataChange(result);
                    }}
                >
                    {Object.keys(GRADE).map(item => (
                        <Select.Option value={Number(item)} key={Number(item)}>
                            {GRADE[item]}
                        </Select.Option>
                    ))}
                </Select>
            )
        },
        {
            title: () => (
                <div className={styles.newFunctionTableHeader}>
                    <div>业务端实现情况</div>
                    <ul>
                        <li>Web端</li>
                        <li>APP端</li>
                        <li>PC端</li>
                    </ul>
                </div>
            ),
            dataIndex: 'terminalScope',
            key: 'terminalScope',
            width: 200,
            render: (_, record) => {
                const { WEB, APP, PC } = record?.terminalScope;
                return (
                    <div className={styles.functionIncidenceWrapper}>
                        {WEB ? <Icon type="check" /> : <Icon type="minus" />}
                        {APP ? <Icon type="check" /> : <Icon type="minus" />}
                        {PC ? <Icon type="check" /> : <Icon type="minus" />}
                    </div>
                );
            }
        },
        {
            title: '授权模板',
            dataIndex: 'roleCodes',
            key: 'roleCodes',
            render: (value, record) => (
                <TreeSelectGroup
                    placeholder="请选择授权模板"
                    value={value}
                    data={manageList?.data || []}
                    onChange={codes => {
                        const result = { ...record, roleCodes: codes };
                        handleRowDataChange(result);
                    }}
                />
            )
        }
    ];


    return (
        <PageHeaderWrapper>
            <Card
            //  title="功能权限编辑" className={styles.cardBox}
            >
                <Alert message="功能权限修改将应用于整个系统，请谨慎操作。" type="warning" showIcon closable />
                <br />
                <Table
                    expandedRowKeys={expandAllRows}
                    loading={loading}
                    rowKey="resourceCode"
                    className={styles.functionListTable}
                    onExpandedRowsChange={e => {
                        setExpandAllRows(e);
                    }}
                    columns={columns}
                    pagination={false}
                    dataSource={rows}
                    expandIcon={({ expanded, onExpand, record }) => {
                        const { children } = record;
                        if (!children) {
                            return <span style={{ width: 14, height: 14 }}></span>;
                        }
                        return expanded ? (
                            <Icon type="caret-right" style={{ marginRight: 5 }} onClick={e => onExpand(record, e)} />
                        ) : (
                            <Icon type="caret-down" style={{ marginRight: 5 }} onClick={e => onExpand(record, e)} />
                        );
                    }}
                />
                <FooterButton saveValue={saveData} submitValue={submitData} beforeSave={async () => {
                    const result = await getFunctionList();
                    const mapList = tree2array(result?.data)
                    const booleanType = mapList.some(item => Object.values(item.draft).length > 0);
                    return booleanType
                }}/>
            </Card>
        </PageHeaderWrapper>
    );
};
export default BatchEdit;
